package com.cilico.components;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SimpleAdapter;

import com.cilico.ConfigManager;
import com.cilico.Mid;
import com.cilico.R;
import com.cilico.utils.Base64;
import com.cilico.utils.ConstantRepository;
import com.cilico.view.DetailView;
import com.cilico.view.BaseView;
import com.cilico.view.FormLayout;

public class UploadFile extends LinearLayout implements Component {

	public String attrName_;
	public String attrValue_;
	BaseView bv_;
	int left_; // Relative left position to the left of the FULL canvas.
	int top_; // Relative left position to the top of the FULL canvas.
	int width_;
	int height_;

	public ImageView imgView_;
	public Button uploadButton_;
	PopupWindow pop_ = null;

	public static final int NONE = 0;
	public static final int PHOTOHRAPH = 1;// 拍照
	public static final int PHOTOZOOM = 2; // 缩放
	public static final int PHOTORESOULT = 3;// 结果
	public static final String IMAGE_UNSPECIFIED = "image/*";

	public UploadFile(Context context, String name, String value) {
		super(context);
		bv_ = (BaseView) context;
		attrName_ = name;
		attrValue_ = value;
		height_ = 100;
		width_ = MAX_WIDTH;
		setLayoutParams(new LinearLayout.LayoutParams(width_, height_));
		setOrientation(LinearLayout.HORIZONTAL);
		initView();
	}

	private void initView() {
		imgView_ = new ImageView(bv_);
		if (TextUtils.isEmpty(attrValue_)) {
			imgView_.setImageResource(R.drawable.login_user_pic);
		} else {
			imgView_.setImageBitmap(base64ToBitmap(attrValue_));
		}
		imgView_.setLayoutParams(new LinearLayout.LayoutParams(100, 100));
		addView(imgView_);

		uploadButton_ = new Button(bv_);
		uploadButton_.setWidth(150);
		uploadButton_.setText("更改头像");
		uploadButton_.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				popWindow();
			}
		});
		addView(uploadButton_);
	}

	/**
	 * 弹出框布局
	 */
	public void popWindow() {
			SimpleAdapter adapter;
			LayoutInflater inflater = (LayoutInflater) bv_.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			ListView listView = (ListView) inflater.inflate(R.layout.sharelist, null, false);
			final List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("logo", null);
			map.put("info", null);
			map.put("title", "请选择");
			map.put("img", null);
			list.add(map);
			map = new HashMap<String, Object>();
			map.put("logo", R.drawable.weibo_sina_logo);
			map.put("info", "通过相册");
			map.put("title", null);
			map.put("img", R.drawable.arr);
			list.add(map);
			map = new HashMap<String, Object>();
			map.put("logo", R.drawable.weibo_renren_logo);
			map.put("info",  "通过拍照");
			map.put("title", null);
			map.put("img", R.drawable.arr);
			list.add(map);

			adapter = new SimpleAdapter(bv_, list, R.layout.shareitem, new String[] { "logo", "info", "title", "img" }, new int[] {R.id.shareLogo, R.id.shareItem, R.id.shareTitle, R.id.shareItemImage });
			listView.setFocusable(false);
			listView.setItemsCanFocus(true);
			listView.setAdapter(adapter);
			listView.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
					Object o = list.get(arg2).get("info");
					if (null != o) {
						pop_.dismiss();
						pop_ = null;
						String temp = o.toString();
						if (temp.equals("通过相册")) {
							photoAlbum();
						} else {
							photograph();
						}
					}
				}
			});

			// 找出屏幕宽度
			WindowManager windowManager = bv_.getWindowManager();
			Display display = windowManager.getDefaultDisplay();
			
			// 设置弹出框相关属性
			pop_ = new PopupWindow(listView, display.getWidth() * 4 / 5, LayoutParams.WRAP_CONTENT, true);
			pop_.setBackgroundDrawable(bv_.getResources().getDrawable(R.layout.sharepopup_corner_style));
			
			pop_.setTouchable(true);
			pop_.setAnimationStyle(R.style.AnimationPreview);  //设置动画
			pop_.setFocusable(true);
			pop_.update(); 
			pop_.showAtLocation(listView, Gravity.CENTER, 0, 0);
		
	}
	
	
	/**
	 *  调用相册
	 */
	public void photoAlbum() {
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
		intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_UNSPECIFIED);
		ConfigManager.currentView_.startActivityForResult(intent, PHOTOZOOM);
	}

	/**
	 *  调用拍照
	 */
	public void photograph() {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "temp.jpg")));
		ConfigManager.currentView_.startActivityForResult(intent, PHOTOHRAPH);
	}

	/**
	 *  上传头像到服务器
	 * @param detailView
	 * @param mid
	 * @param bitmap
	 * @param localPath
	 */
	public void upload(final DetailView detailView, final Mid mid, final Bitmap bitmap, final String localPath) {
		final StringBuffer sb = new StringBuffer(ConfigManager.UPLOAD_HEAD__PORTRAIT_URI);
		sb.append("head_pic=");
		String data = bitmaptoBase64(bitmap);
		sb.append(data);
		mid.waitDialog_.addFgTask(detailView, new WaitDialog.Task(0) {
			public void run(WaitDialog dlg) throws Exception {
				String reply = mid.hm_.sendRequest(sb.toString(), this);
			}

			public void onSuccess(WaitDialog dlg) {
//				Toast.makeText(ConfigManager.currentView_, "上传成功", Toast.LENGTH_SHORT).show();
				super.onSuccess(dlg);
			}

			public void onFailure(WaitDialog dlg) {
//				Toast.makeText(ConfigManager.currentView_, "上传失败，请重试", Toast.LENGTH_SHORT).show();
				super.onFailure(dlg);
			}
		}, false);
		mid.waitDialog_.setText(ConstantRepository.getWaitText(ConstantRepository.SENDING_DATA));
	}

	/**
	 *  将bitmap转换成base64
	 * @param bitmap
	 * @return
	 */
	public String bitmaptoBase64(Bitmap bitmap) {
		String string = null;
		ByteArrayOutputStream bStream = new ByteArrayOutputStream();
		bitmap.compress(CompressFormat.PNG, 100, bStream);
		byte[] bytes = bStream.toByteArray();
		string = Base64.encodeToString(bytes, Base64.DEFAULT);
		return string;
	}
	
	/** 
	 * base64转为bitmap 
	 * @param base64Data 
	 * @return 
	 */  
	public Bitmap base64ToBitmap(String base64Data) {
	    byte[] bytes = Base64.decode(base64Data, Base64.DEFAULT);
	    return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
	}  

	/**
	 *  保存截取后的图片
	 * @param bitmap
	 * @return
	 * @throws Exception
	 */
	public String storeImg(Bitmap bitmap) throws Exception {
		String path = Environment.getExternalStorageDirectory().getPath() + File.separator + "cilico/portait/";
		File file = new File(path + "head_portait.png");
		if (file.exists()) {
			file.delete();
		}
		if (!new File(path).exists()) {
			new File(path).mkdirs();
		}
		file.createNewFile();
		FileOutputStream fos = new FileOutputStream(file);
		bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
		fos.flush();
		fos.close();
		System.gc();
		return file.getPath();
	}

	/**
	 *  将图片变圆
	 * @param bitmap
	 * @param pixels
	 * @return
	 */
	public Bitmap toRoundCorner(Bitmap bitmap, int pixels) {
		Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);
		Canvas canvas = new Canvas(output);

		final int color = 0xff424242;
		final Paint paint = new Paint();
		final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
		final RectF rectF = new RectF(rect);
		final float roundPx = pixels;

		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

		paint.setXfermode((new PorterDuffXfermode(Mode.SRC_IN)));
		canvas.drawBitmap(bitmap, rect, rect, paint);
		return output;
	}

	@Override
	public String getContentText() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void setContentText(String text) {
		// TODO Auto-generated method stub

	}

	@Override
	public void shrinkWidth() {
		// TODO Auto-generated method stub

	}

	@Override
	public void cleanText() {
		// TODO Auto-generated method stub

	}

	@Override
	public void mould() {
		// TODO Auto-generated method stub

	}

	@Override
	public void setCmpWidth(int width) {
		// TODO Auto-generated method stub

	}

	@Override
	public int getCmpWidth() {
		// TODO Auto-generated method stub
		return this.getWidth();
	}

	@Override
	public void setCmpHeidht(int height) {
		// TODO Auto-generated method stub

	}

	@Override
	public int getCmpHeight() {
		// TODO Auto-generated method stub
		return this.getHeight();
	}

	@Override
	public void setCssStyle(CssStyle style) {
		// TODO Auto-generated method stub

	}

	@Override
	public View getCmpView() {
		// TODO Auto-generated method stub
		return this;
	}

	@Override
	public void setInTable(boolean inTable) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean isInTable() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public CssStyle getCssStyle() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void releaseResource(View view) {
		// TODO Auto-generated method stub

	}

	@Override
	public void setForm(FormLayout formLayout) {
		// TODO Auto-generated method stub

	}

	@Override
	public FormLayout getForm() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void setEncrypt(String encrypt) {
		// TODO Auto-generated method stub

	}

}
